#ifndef FLVAPI_H
#define FLVAPI_H
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>
#include"faacapi.h"
#define FLV_FLAG_VIDEO 0x01
#define FLV_FLAG_AUDIO 0x04
#define FLV_TYPE_VIDEO		9
#define FLV_TYPE_AUDIO		8
#define FLV_TYPE_SCRIPTDATA	18
typedef struct _flvframe{
uint32_t type;
uint32_t timestamp;
uint32_t datalength;
uint32_t info;
long	 datapos;
}flvframe;
//读取相关
//0成功-1失败 成功定位到第一帧开始
int FlvCheckHead(FILE*fp);
//获取下一帧信息 跳过帧头 定位到数据开始
int FlvGetNextFrame(FILE*fp,flvframe*frameinfo);

//写文件相关
//写flv头部
int FlvWriteHead(FILE*fp,int flag);
//写flv帧数据
int FlvWriteFrame(FILE*fp,flvframe*frameinfo,const char*data);

int FlvWriteFAACInfo(FILE*flvfile,ADSTHEADINFO info,uint32_t timestamp);
int FlvWriteFAACInfoFrame(FILE*flvfile,uint8_t*buffer,uint32_t buffersize,uint32_t timestamp);
int FlvWriteFAACFrame(FILE*flvfile,uint8_t*buffer,uint32_t buffersize,uint32_t timestamp);

//写SPS，PPS信息
int FlvWriteX264Info(FILE*flvfile,uint8_t*sps,uint32_t spssize,uint8_t*pps,uint32_t ppssize,uint32_t timestamp);
//写入帧信息，这里buffer头4字节不是nal_size，需补充
int FlvWriteX264Frame(FILE*flvfile,uint8_t*buffer,uint32_t buffersize,uint8_t bKeyFrame,uint32_t timestamp);

const char*FlvGetAudioInfo(int audioinfo);
const char*FlvGetVideoInfo(int videoinfo);

//涉及到的通用函数
#define HTON16(x)  (((x)>>8&0xff)|((x)<<8&0xff00))
#define HTON24(x)  (((x)>>16&0xff)|((x)<<16&0xff0000)|(x)&0xff00)
#define HTON32(x)  (((x)>>24&0xff)|((x)>>8&0xff00)|((x)<<8&0xff0000)|((x)<<24&0xff000000))
#define HTONTIME(x) (((x)>>16&0xff)|((x)<<16&0xff0000)|(x)&0xff00ff00)
#define MAKETYPE(a,b,c,d) (((a)&0xff)|((b)<<8&0xff00)|((c)<<16&0xff0000)|((d)<<24&0xff000000))
//-1错误 0正确
int WriteU8(uint32_t u8,FILE*f);
int WriteU16(uint32_t u16,FILE*f);
int WriteU24(uint32_t u24,FILE*f);
int WriteU32(uint32_t u32,FILE*f);
int WriteTime(uint32_t utime,FILE*f);

int PeekU8(uint32_t*u8,FILE*f);

int ReadU8(uint32_t*u8,FILE*f);
int ReadU16(uint32_t*u16,FILE*f);
int ReadU24(uint32_t*u24,FILE*f);
int ReadU32(uint32_t*u32,FILE*f);
int ReadTime(uint32_t*utime,FILE*f);

const char*ReadU8FromBuff(uint32_t*u8,const char*buff);
const char*ReadU16FromBuff(uint32_t*u16,const char*buff);
const char*ReadU32FromBuff(uint32_t*u32,const char*buff);

const char*WriteBuff(FILE*fp,const char*buff,uint32_t len);
char*WriteU16ToBuff(uint32_t u16,char*buff);
char*WriteU32ToBuff(uint32_t u32,char*buff);

typedef struct _BitStream{
const uint8_t*data;//数据
int len;//数据长度
int pos;//当前位置
int bit;//当前字节的位数
}BitStream;
//-1读取错误
int ReadBitData(BitStream*info,int bits);
int ReadExData(BitStream*info);
#endif